// pages/like/like.js
import { get } from 'mobx-miniprogram'
import {createStoreBindings} from 'mobx-miniprogram-bindings'
import {store} from '../../store/sotre'

const app = getApp()

Page({
  // 结算商品
  buyGoods(){
    if(!app.globalData.isUserInfo){
      wx.showToast({
        title: '您还未登录哦',
        icon: 'error'
      })
      return
    }
    
    let isExist = this.data.goods.some(item => item.isSelected === true)
    if(!isExist){
      wx.showToast({
        title: '请至少选择一件商品',
        duration: 1500,
        icon: 'none'
      })
      return
    }

    app.globalData.settleGoods = []
    let obj = this.data.goods.filter(item => item.isSelected === true)
    console.log(obj);
    app.globalData.settleGoods = obj


    wx.navigateTo({
      url: '../../subpkg_settle/pages/settle',
    })

  },
  /**
   * 页面的初始数据
   */
  data: {
    isShowDia: true, // 加载动画
    navBar: false, // 导航栏显示控制
    check_all_price: 0, // 全选商品价格
    isCheckAll: false, // 是否全选
    actionSheetData: {}, // 需要修改的商品详情
    goods: [], // 购物车所有商品
    index: 0
  },
  
  // 页面滚动
  onPageScroll(e){
    wx.createSelectorQuery().select('.tit').boundingClientRect(rect => {
      if(e.scrollTop >= rect.height){ this.setData({ navBar: true }) }
      else{ this.setData({ navBar: false }) }
    }).exec()
  },
  // 每个商品选中态
  upDataCheck(e){
    const idx = e.currentTarget.dataset.idx;
    let obj = this.data.goods.map((item,index) => {
      if (index === idx) {
        return {...item, isSelected: !item.isSelected};
      }
      return item
    })
    this.setData({ goods: obj })
    wx.setStorageSync('goodsList', this.data.goods)
    // 更新全选
    this.updateCheckAll()
    // 更新价格合计
    this.updatePrice()
    // 更新tabbar上的数量
    this.checkGoodsNum()
  },
  // 选中商品数量
  checkGoodsNum(){
    let storageGoods = wx.getStorageSync('goodsList') || []
    let num = storageGoods.filter(item => item.isSelected === true).length
    store.updateCheckNum(num)
  },
  // 删除商品
  delGoods(e){
    const id = e.currentTarget.dataset.goodsid
    const index = e.currentTarget.dataset.index
    
    wx.showModal({
      title: '提示',
      content: '是否确定删除？',
      confirmColor: '#000000',
      cancelColor: '#858585',
      success: res => {
        if (res.confirm) {
          // 全部删除
          if(id === -1){
            this.setData({ goods: [] })
            wx.setStorageSync('goodsList', this.data.goods)
            this.checkGoodsNum()
            return
          }
          // 单个删除
          const toRemove = this.data.goods.findIndex(item => item._id === id && item.actIdx === index)
          const updateGoods = [...this.data.goods]

          updateGoods.splice(toRemove, 1)

          this.setData({ goods: updateGoods })
          wx.setStorageSync('goodsList', updateGoods)
          
          this.updatePrice()
          this.checkGoodsNum()
          this.updateCheckAll()
        }
      }
    })
  },
  // 打开商品系列面板
  updateInfo(e){
    let obj = this.data.goods
    let goodsId = e.currentTarget.dataset.goodsid
    let actIdx = e.currentTarget.dataset.idx
    let index = e.currentTarget.dataset.index
    let result = obj.find(item => item._id === goodsId && item.actIdx === actIdx);

    this.setData({ 
      showGoodsAction: true,
      actionSheetData: result,
      index: index
    })
  },
  // 跳转商城页
  goPage(){
    wx.switchTab({
      url: '../list/list',
    })
    this.updataActive(1)
  },
  // 商品全选
  checkAllGoods(e){
    // 全选/反选
    if(!this.data.isCheckAll && this.data.goods.length > 0){
        this.data.goods.forEach(item => {
          item.isSelected = true
        })
    }else if(this.data.goods.length > 0){
        this.data.goods.forEach(item => {
          item.isSelected = false
        })
    }
    this.setData({
      isCheckAll: !this.data.isCheckAll,
      goods: this.data.goods
    })
    wx.setStorageSync('goodsList', this.data.goods)
    this.updatePrice()
    this.checkGoodsNum()
  },
  // 自动判断商品是否全部选中
  updateCheckAll(){
    if(this.data.goods.length <= 0 ) return
    // 是否全部选中
    let isAllSelect = this.data.goods.every(item => item.isSelected)
    if(isAllSelect){
      this.setData({ isCheckAll: true })
    }else{
      this.setData({ isCheckAll: false })
    }
  },
  // 选中任意一个后价格更新
  updatePrice(){
    // if(this.data.goods.length <= 0) return
    let goods = this.data.goods || []
    let accountPrice = 0
    goods.forEach(item => {
      if(item.isSelected){
        accountPrice += Number(item.every_price[item.actIdx])
      }
    })
    this.setData({
      check_all_price: accountPrice.toFixed(2)
    })
  },
  // 跳转商品详情页
  goDetail(e){
    let id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `../../subpkg_goods_detail/pages/detail?goods_id=${id}`,
    })
  },
  // 获取本地存储数据
  updateGoods(){
    this.setData({
      goods: wx.getStorageSync('goodsList')
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.storeBindings = createStoreBindings(this, {
      store,
      fields: ['checkNum'],
      actions: ['updataActive','updateCheckNum']
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    this.updateCheckAll()
    this.updatePrice()
    this.checkGoodsNum()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.updateGoods()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})